/*
 * FileName：BaseCtrl.java 
 * <p>
 * Copyright (c) 2017-2020, <a href="http://www.webcsn.com">hermit (1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.smart.primary.common.common;

import com.alibaba.fastjson.JSONObject;
import com.smart.buss.ctrl.BussUserController;
import com.smart.buss.service.BussUserService;
import com.smart.buss.vo.BussUser;
import com.smart.primary.common.page.Page;
import com.smart.primary.common.util.*;
import com.smart.primary.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Controller基础公共类
 *
 * @author hermit
 * @date 2017 -06-28 20:41:23
 */
public class BaseCtrl {
	private final static Logger logger= Logger.getLogger(BaseCtrl.class);
    @Resource
    protected HttpServletRequest request;
    
    @Resource
    protected HttpServletResponse response;
    @Autowired
	private BussUserService bussUserService;
	@Autowired
	private UserService sysUserService;

    
    /**
     * 初始化属性，在每个方法执行前执行该赋值方法
     *
     * @param request
     * @param response
     * @author hermit
     * @date 2017 -10-17 15:57:10
     */
    @ModelAttribute
    public void setAttribute(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    public AjaxResult getResult(Page page, Object data){
        AjaxResult result = new AjaxResult();
        Page newPage = new Page();
        newPage.setPage(page.getPage());
        newPage.setPageSize(page.getPageSize());
        newPage.setTotal(page.getTotal());
        newPage.setTotalPage(page.getTotalPage());
        result.setPage(newPage);
        result.setData(data);
        result.setSuccess(true);
        return result;
    }

    protected static boolean validate(HttpServletRequest request, String validateCode) {
        if(StringUtil.isBlank(validateCode)) {
            return false;
        } else {
            String code = (String)request.getSession().getAttribute("adminVerifyCode");
            return validateCode.toUpperCase().equals(code);
        }
    }

    public static Date stringToDate(String strTime){
        if(StringUtils.isBlank(strTime)){
            return null;
        }
        strTime=strTime.replace("T"," ");
        Date date = null;
        try {
            if(checkDate(strTime,"yyyy-MM-dd HH:mm:ss")){
                date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strTime);
            }else if(checkDate(strTime,"yyyy-MM-dd HH")){
                date = new SimpleDateFormat("yyyy-MM-dd HH").parse(strTime);
            }else if(checkDate(strTime,"yyyy-MM-dd")){
                date = new SimpleDateFormat("yyyy-MM-dd").parse(strTime);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String dateToString(Date date){
		if(date==null){
			return null;
		}
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}

	public static String dateToString2(Date date){
		if(date==null){
			return null;
		}
		return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
	}
	public static String dateToStr(Date date){
		if(date==null){
			return null;
		}
		return new SimpleDateFormat("yyyy-MM-dd").format(date);
	}
    public static boolean checkDate(String strTime,String formatType) {
        if(StringUtils.isBlank(strTime) || StringUtils.isBlank(formatType)){
            return false;
        }
        boolean bool=true;
        try {
            new SimpleDateFormat(formatType).parse(strTime);
        } catch (ParseException e) {
            bool=false;
        }
        return bool;
    }

    public static String listToStr(List list){
        if (list==null || list.size()==0) {
            return "";
        }
        StringBuilder result=new StringBuilder();
        for (Object str : list) {
            result.append((str+",").trim());
        }
        return result.substring(0,result.length()-1);
    }

    
    public String getUserMobile() {
    	String deviceToken = getCook(request,"deviceToken");
    	if(StringUtils.isBlank(deviceToken) || "null".equalsIgnoreCase(deviceToken)) {
			return "";
		}
    	String fcode=getCook(request,"fcode");
    	String code = setSessionCache(deviceToken,fcode);
    	return code;
    }

	public String getqudao() {
		String deviceToken = getCook(request,"deviceToken");
    	if(StringUtils.isBlank(deviceToken) || "null".equalsIgnoreCase(deviceToken)) {
			return "";
		}
    	String channel = RedisUtils.getJedis().get(deviceToken+"_user_channel");
		return channel;
	}

    
    public String setSessionCache(String deviceToken,String fcode) {
    	try {
    		String phone="";
    		String channel="";
    		//查数据库看是否有deviceToken 此用户
			String mKey = MD5Util.MD5Encode(deviceToken+"_6341c941-21bd-4212-b133-80fd0f818fb2", "UTF-8");
			String httpUrl = PropertiesUtil.getString("res.web.url")+"/dk/task/checkLogin.do?deviceToken="+deviceToken+"&key="+mKey;
			String res = HttpClientUtils.sendHttpGet(httpUrl);
			//logger.info("setSessionCache httpUrl:"+httpUrl);
			//logger.info("setSessionCache res:"+res);
			JSONObject obj = JSONObject.parseObject(res);
			String respCode = obj.get("respCode")+"";
			if("0".equals(respCode)) {
				JSONObject data = obj.getJSONObject("data");
				phone = data.getString("mobile");
				channel = data.getString("channel");
				if(StringUtils.isBlank(fcode)){
					fcode = data.getString("fcode");
				}
			}
			//logger.info("redis 中"+deviceToken+"_sysc_login的值：" + phone);
			//logger.info("redis 中"+deviceToken+"_sysc_fcode的值：" + fcode);
			if(StringUtil.isNotEmpty(phone)) {
				/**
				 *
				 *  查询用户策略优先手机号
				 */
				BussUser quser = null;
				List<BussUser> quserList= null;
				List<BussUser> mobileUserList= null;
				
				
				
				
				if(StringUtil.isNotEmpty(deviceToken)) {
					BussUser bu=new BussUser();
					bu.setDeviceToken(deviceToken);
					quserList= bussUserService.queryList(bu);
				}
				
				if(StringUtil.isNotEmpty(phone)) {
					BussUser buMobile=new BussUser();
					buMobile.setPhone(phone);
					mobileUserList= bussUserService.queryList(buMobile);
				}
				
				if(mobileUserList!=null && mobileUserList.size()>0){
					quser = mobileUserList.get(0);
					quser.setDeviceToken(deviceToken);
				}else if(quserList != null && quserList.size()>0){
					quser = quserList.get(0);
				}
				String code="";  //
				BussUser bu=new BussUser();
				if(quser==null){ // 创建新用户
					// 设置邀请码
					code=bussUserService.getCode();
					bu.setCode(code);
					// 设置邀请码为id
					bu.setId(code);
					bu.setName(code);
					//生成二维码
					String twocode=bussUserService.getCodeImg(code,request);
					bu.setTwoCode(twocode);
					// 看是否有 邀请码 有的话添加
					if(StringUtils.isNotBlank(fcode) && !"null".equalsIgnoreCase(fcode)){
						bu.setFcode(fcode);
						// 设置 fid
						BussUser fuser=new BussUser();
						fuser.setCode(fcode);
						BussUser qfuser= bussUserService.queryObject(fuser);
						if(qfuser!=null){
							bu.setFid(qfuser.getId());
						}
					}
					if(StringUtils.isNotBlank(phone) && !"null".equalsIgnoreCase(phone)){
						bu.setPhone(phone);
					}
					if(StringUtils.isNotBlank(deviceToken) && !"null".equalsIgnoreCase(deviceToken)){
						bu.setDeviceToken(deviceToken);
					}
					bu.setChannel(channel);
					bussUserService.insert(bu);
				}else {
					code=quser.getId();
					channel = quser.getChannel();
					// 看是否有手机号  没有的话设置
					if(StringUtil.isBlank(quser.getPhone())){
						String userMobile= RedisUtils.getJedis().get(deviceToken+"_sysc_login");
						if(StringUtils.isNotBlank(userMobile) && !"null".equalsIgnoreCase(userMobile)){
							if(userMobile.length()>11){
								userMobile=userMobile.substring(userMobile.length()-11);
							}
							quser.setPhone(userMobile);
						}
					}
					if(StringUtil.isNotBlank(deviceToken) ){
						quser.setDeviceToken(deviceToken);
					}
					bussUserService.update(quser);
				}
				 
		    	RedisUtils.getJedis().set(deviceToken+"_user_code",code);
		    	if(StringUtils.isNotEmpty(channel)) {
		    		RedisUtils.getJedis().set(deviceToken+"_user_channel",channel);
		    	}
				//logger.info("设置 手机号session：" + code);
				return code;
			}
    	} catch (Exception e) {
			e.printStackTrace();
		}
    	return "";
	}
    
	public String getCook(HttpServletRequest request,String str){
		Cookie[] cookies = request.getCookies();
		String token = "";
		if(cookies!=null){
			for (Cookie cookie : cookies) {
				if(cookie.getName().equalsIgnoreCase(str)){
					token = cookie.getValue();
				}
			}
		}
		//logger.info("cookie 中deviceToken的值：" + token);
		return token;
	}


}
